//
//  GYWebviewctl.m
//  ChineseMedicineForUsers
//
//  Created by Fuhao on 2017/2/22.
//  Copyright © 2017年 Fuhao. All rights reserved.
//

#import "GYWebviewctl.h"
#import <UShareUI/UShareUI.h>

 #import <WebKit/WebKit.h>
 @interface GYWebviewctl ()<WKNavigationDelegate,WKUIDelegate,UIGestureRecognizerDelegate>
@property(nonatomic ,strong) UIBarButtonItem *backBtn;
@property(nonatomic ,strong) UIBarButtonItem *closeBtn;
@property (weak, nonatomic) CALayer *progresslayer;

@property (nonatomic, strong) NSString *titleName;
@end

@implementation GYWebviewctl{
    WKWebView *_webView;
    id<UIGestureRecognizerDelegate> _delegate;
}
-(void)CreateProgress{
    //进度条
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 3)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = KMainColor.CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KBackColor;
    _webView = [WKWebView new];
//    [[WKWebView alloc] initWithFrame:self.view.frame];
    
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    //开了支持滑动返回
    _webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:_webView];
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NavHeight);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    self.titleName = @"";
    if(_gyweb == GYWebviewctlFuwu){
        self.titleName = @"服务协议";
         [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }else if(_gyweb == GYWebviewctlSep){
        self.titleName = @"关于我们";
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }else if(_gyweb == GYWebviewctlUsr){
        self.titleName = @"隐私政策";
          [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }else if(_gyweb == GYWebviewctlLunbo){
        self.titleName = @"产品";
         [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }else if(_gyweb == GYWebviewctlSchool){
        //学校
        [self setNav];
        self.titleName = self.schoolName;
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }else if(_gyweb == GYWebviewctlTitle){
        //文章
        [self setNav];
        self.titleName = self.schoolName;
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.jumpUrl]]];
    }
    self.navigationItem.title = self.titleName;
    [self CreateProgress];
    
}

- (void) setNav {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"icon_share"] style:UIBarButtonItemStyleDone target:self action:@selector(rightClick)];
    self.navigationItem.rightBarButtonItem = rightBtn;
}
//分享
- (void)rightClick {
    //显示分享面板
     [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        [self shareImageAndTextToPlatformType:platformType];
    }];
}
- (void)shareImageAndTextToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享标识
     //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = @"";
    
    NSString *desc = @"";
     if(_gyweb == GYWebviewctlTitle){
         //文章
         desc = @"";
     }else if(_gyweb == GYWebviewctlSchool){
         //文章
         desc = [NSString stringWithFormat:@"从这个角度看%@真是一览无遗",self.schoolName];
     }
    //创建图片内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.schoolName descr:desc thumImage:[UIImage imageNamed:@"icon_logo"]];
    NSString *str = [NSString stringWithFormat:@"%@",self.jumpUrl];
    shareObject.webpageUrl = str;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //这里修改导航栏的标题，动态改变
//    self.title = webView.title;
    self.title = self.titleName;
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    DLog(@"%@",webView);
    DLog(@"%@",navigationResponse);
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    self.title = self.titleName;
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    if (navigationAction.navigationType==WKNavigationTypeBackForward) {
        //判断是返回类型 //同时设置返回按钮和关闭按钮为导航栏左边的按钮 这里可以监听左滑返回事件，仿微信添加关闭按钮。
        self.navigationItem.leftBarButtonItems = @[self.backBtn, self.closeBtn];
        //可以在这里找到指定的历史页面做跳转 //
        if (webView.backForwardList.backList.count>0) {
            //得到栈里面的list  //
            WKBackForwardListItem * item = webView.backForwardList.currentItem;
            //得到现在加载的list //
            for (WKBackForwardListItem * backItem in webView.backForwardList.backList) {
                //循环遍历，得到你想退出到 //
                //添加判断条件 //
                [webView goToBackForwardListItem:[webView.backForwardList.backList firstObject]];
            }
        }
    }
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
}
-(void)backNative{
    //判断是否有上一层H5页面
    if ([_webView canGoBack]) {
        //如果有则返回
        [_webView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
            self.navigationItem.leftBarButtonItems = @[self.backBtn, self.closeBtn];
        } else {
            [self closeNative];
        }
}
-(void)closeNative{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UIBarButtonItem *)backBtn
{
    if (!_backBtn) {
        _backBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"更多(1)"] style:UIBarButtonItemStyleDone target:self action:@selector(backNative)];
    }
    return _backBtn;
}

- (UIBarButtonItem *)closeBtn
{
    if (!_closeBtn) {
        _closeBtn = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
    }
    return _closeBtn;
}
#pragma mark - WKUIDelegate
//1.创建一个新的WebVeiw
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.alpha = 1;

}
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    
    
    DLog(@"%s--configuration is %@ \n and navigationAction is %@\n and windowFeatures is %@",__FUNCTION__,configuration,navigationAction,windowFeatures);
    return webView;
}

//2.WebVeiw关闭（9.0中的新方法）
- (void)webViewDidClose:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0)){
    
    DLog(@"%s-",__FUNCTION__);
    
}

//3.显示一个JS的Alert（与JS交互）
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    DLog(@"弹窗alert");
    DLog(@"%@",message);
    DLog(@"%@",frame);
    [self.view makeToast:message];
    completionHandler();
}

//4.弹出一个输入框（与JS交互的）
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    DLog(@"弹窗输入框");
    DLog(@"%@",prompt);
    DLog(@"%@",defaultText);
    DLog(@"%@",frame);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //这里必须执行不然页面会加载不出来
        completionHandler(@"");
    }];
    UIAlertAction *a2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"%@",
             [alert.textFields firstObject].text);
        completionHandler([alert.textFields firstObject].text);
    }];
    [alert addAction:a1];
    [alert addAction:a2];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        DLog(@"%@",textField.text);
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

//5.显示一个确认框（JS的）
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    DLog(@"弹窗确认框");
    DLog(@"%@",message);
    DLog(@"%@",frame);
    
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

///加载进度实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
            return;
        }
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
        if ([change[@"new"] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)dealloc{
    [(WKWebView *)_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    DLog(@"%s",__func__);
}
@end
